
define(['template','request','jquery','cookie'], (template,request) => {
   class Header {
     constructor () {
      //  this.load()
       this.load().then(() => {
         // 执行加载成功之后的逻辑
         this.search()
         this.getTabs()
         this.calcCartNum()
         this.yanZheng()
       })
     }
 
     // 加载头部html
     load () {
       return new Promise(resolve => {
         // 加载成功之后resolve
         $('header').load('/html/modules/header.html', resolve)
       }) 
     }
     // 完成搜索功能
     search () {
       this.$input = $('#input_search')
       console.log(this.$input)
       this.$input.on('keyup', () => {
         console.log(this.$input.val())
         // TODOS：jsonp接口
       })
     }

   //本地json获取头部导航栏
     getTabs(){
          class HeaderNav{
            constructor(){
             this.getHeaderNav()
            }
            getHeaderNav () {
             $.get('/libs/json/headernav.json', resp =>{
               this.renderHeaderNav(resp)
              //  console.log(resp)
             })
           }
           renderHeaderNav (list) {
             const id = window.location.hash.slice(1)
             const html = template('headerNavTemplate',{ list,id })
             $('#headerNavList').prepend(html)
           }
          }
          new HeaderNav()
     }
     calcCartNum(){
       let cartList = localStorage.getItem('cart')
       if(cartList){
        cartList = JSON.parse(cartList)
        let num = cartList.reduce((total,cart) =>{
          total+=cart.num
          return total
        },0)
        $('#cartnum').html(num)
       }else{
         $('#cartnum').html(0)
       }
     }
     //验证cookie里面是否已经存在用户信息
     yanZheng(){
       let userInfo=localStorage.getItem('userInfo')
       if(userInfo){
         $('.dl').css({'display':'none'})
         $('.zc').css({'display':'none'})
         $('.is-login').css({'display':'block'})
         userInfo=JSON.parse(userInfo)
        //  console.log(decodeURI(encodeURI(userInfo.username)))
         $('#user-name').html(userInfo.username)
       }
       $('#logout-btn').on('click',function(){
         if(confirm('确认注销吗?')){
           $.cookie('userInfo','',{expires:-1,path:'/'})
           $('.dl').css({'display':'block'})
           $('.zc').css({'display':'block'})
           $('.is-login').css({'display':'none'})
         }
       })
     }
   }
   return new Header()
 });

 


